<template>
    <Dialog v-model="dialogVisible" :title="dialogTitle" width="600">
        <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="100px" :disabled="disabled">
          <div>
            <h3>基本信息</h3>
          <el-form-item label="房间号" prop="number">
                <el-input v-model="formData.number" type="text" clearable placeholder="请输入房间号"/>
            </el-form-item>
            <el-form-item label="琴房类型" prop="typeId">
                <el-select v-model="formData.typeId" placeholder="请选择琴房类型" style="width: 100%" clearable>
                    <el-option v-for="item in roomTypes" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="教学楼" prop="buildingId">
                <el-select v-model="formData.buildingId" placeholder="请选择教学楼" style="width: 100%" clearable>
                    <el-option v-for="item in buildings" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="门禁类型" prop="accessType">
                <el-select v-model="formData.accessType" placeholder="请选择门禁类型" @click="getDictOption" multiple clearable>
                    <el-option v-for="dict in dictOption" :label="dict.label" :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="绑定设备" prop="deviceId" v-if="equipmentVisible">
                <el-select v-model="formData.deviceId" placeholder="请选择门禁设备" filterable>
                    <el-option v-for="item in devices" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="所属楼层" prop="floor">
                <el-input-number v-model="formData.floor" :min="1"/>
            </el-form-item>
            <el-form-item label="预约人数" prop="subscribeNum">
              <el-input-number v-model="formData.subscribeNum" :min="1"/>
            </el-form-item>
            <el-form-item label="对外预约状态" prop="externalSubStatus">
              <el-radio-group v-model="formData.externalSubStatus" @change="handleExternalSubStatusChange">
                <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.YXT_EXTERNAL_SUB_STATUS)" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="formData.status">
                    <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.YXT_ROOM_STATUS)" :key="dict.value" :label="dict.value">
                        {{ dict.label }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
          </div>
        </el-form>

<!--      <div v-if="isCreate">-->
<!--      &lt;!&ndash; 密码管理 &ndash;&gt;-->
<!--      <h3>密码管理</h3>-->
<!--      <div style="margin-bottom: 20px;">-->
<!--        <el-button type="primary" plain  @click="handlePasswordAdd">-->
<!--          <Icon class="mr-5px" icon="ep:plus"/>-->
<!--          新增密码-->
<!--        </el-button>-->
<!--      </div>-->
<!--      <el-table :data="passwordList" v-loading="passwordLoading" style="width: 100%">-->
<!--        <el-table-column prop="password" label="密码"/>-->
<!--        <el-table-column label="密码有效期" align="center" width="300px">-->
<!--          <template #default="scope">-->
<!--               <span v-if="scope.row.availableStartTime && scope.row.availableEndTime">-->
<!--                {{ scope.row.availableStartTime }} 至 {{ scope.row.availableEndTime }}-->
<!--               </span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :formatter="dateFormatter" prop="createTime" label="创建时间"/>-->
<!--        <el-table-column prop="remark" label="备注"/>-->
<!--        <el-table-column label="操作" align="center" width="150px">-->
<!--          <template #default="scope">-->
<!--            <el-space>-->
<!--              &lt;!&ndash;todo 删除逻辑 需要确认&ndash;&gt;-->
<!--              <el-button @click="handlePasswordDelete(scope.row)" type="danger"-->
<!--                         size="small">-->
<!--                删除-->
<!--              </el-button>-->
<!--            </el-space>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--      </el-table>-->
<!--      <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo"-->
<!--                  :total="passwordTotal" @pagination="getPasswordList"/>-->
<!--      </div>-->
      <template #footer>
            <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="dialogVisible = false">取 消</el-button>
        </template>
    </Dialog>
</template>
<script lang="ts" setup>
import {useBuildingApi} from "@/api/yxt/building";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import {useRoomApi, useRoomPasswordApi, useRoomTypeApi} from "@/api/yxt/room";
import {useConfirm, useMessage} from "@/components/Notice";
import {useEquipmentApi} from "@/api/yxt/supplier";
import {dateFormatter} from "@/utils/formatTime";
import {ref} from "vue";

defineOptions({name: 'YxtExclusiveRoomForm'})

const {t} = useI18n()
const roomApi = useRoomApi();
const buildingApi = useBuildingApi();
const roomTypeApi = useRoomTypeApi();
const equipmentApi = useEquipmentApi();
const roomPasswordApi = useRoomPasswordApi();

const disabled = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const isCreate = ref(true)
const formType = ref('')
const dictOption = ref([])
const passwordList = ref([]) // 密码列表的数据
const passwordLoading = ref(false) // 列表的加载中
const passwordTotal = ref(0)// 列表的总页数
const initParam = ref({
  roomId:undefined
})
const formData = ref({
    id: undefined,
    number: '',
    typeId: undefined,
    roomType: 1,
    buildingId: undefined,
    floor: undefined,
    subscribeNum: 1,
    accessType: Array<number>(),
    deviceId: '',
    externalSubStatus: 0,
    status: 4
})

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  roomId: initParam.roomId
})

const equipmentVisible = computed(() => {
  return formData.value.accessType.includes(2) || formData.value.accessType.includes(3)
    || formData.value.accessType.includes(4) || formData.value.accessType.includes(5);
})

const formRules = reactive({
    number: [{required: true, message: '房间号不能为空', trigger: ['blur', 'change']}],
    buildingId: [{required: true, message: '教学楼信息不能为空', trigger: ['blur', 'change']}],
    typeId: [{required: true, message: '请选择琴房类型', trigger: ['blur', 'change']}],
    accessType: [{required: true, message: '请选择门禁类型', trigger: ['blur', 'change']}],
    floor: [{required: true, message: '请选择所属楼层', trigger: ['blur', 'change']}],
    deviceId: [
      {
        required: equipmentVisible,
        message: '绑定设备不能为空',
        trigger: 'change',
      },
    ]
})

// 处理外部预约状态变化的逻辑
const handleExternalSubStatusChange = (newValue) => {
  if (newValue === 0) {
    // 如果“对外预约状态”选择为关闭，自动设置“状态”为锁定中
    formData.value.status = 4;
  } else {
    // 否则，状态可以为空或其他值
    formData.value.status = 1;  // 或者设为默认值
  }
};

const formRef = ref()
const roomTypes = ref<Array<any>>([])
const buildings = ref<Array<any>>([])
const devices = ref<Array<any>>([])

const open = async (type: string, id?: number) => {
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
    formType.value = type
    resetForm()
    getDictOption()
    if (id) {
        formLoading.value = true
        try {
            formData.value = await roomApi.getObj(id)

        } finally {
            if (type === 'view') disabled.value = true;
            formLoading.value = false
        }
      initParam.roomId = id;
      queryParams.roomId = id;
      getPasswordList(id);
      isCreate.value = false;
    }
    getDevices(id);
    roomTypes.value = await roomTypeApi.getRoomTypeList();
    buildings.value = await buildingApi.getSimpleList();
}
defineExpose({open})

async function getDevices(roomId: any) {
    devices.value = await equipmentApi.getSimpleList({
        id: roomId,
        update: formType.value == 'update'
    });
}

async function getDictOption() {
  dictOption.value = getIntDictOptions(DICT_TYPE.YXT_ROOM_ACCESS_TYPE)
  // 过滤掉 status 为 0 的元素
  dictOption.value = dictOption.value.filter(dict => dict.status !== 1);
}

const emit = defineEmits(['success'])
const submitForm = () => {
    if (formType.value === 'view') {
        return dialogVisible.value = false
    }

    formRef.value?.validate(async (valid: any) => {
        if (valid) {
            formLoading.value = true
            try {
                const data = formData.value
                if (formType.value === 'create') {
                    await roomApi.createObj(data);
                    useMessage(t('common.createSuccess'));
                } else {
                    await roomApi.updateObj(data);
                    useMessage(t('common.updateSuccess'));
                }
                dialogVisible.value = false;
                emit('success');
            } finally {
                formLoading.value = false;
            }
        }
    });
}

const resetForm = () => {
    roomTypes.value = [];
    buildings.value = [];
    disabled.value = false;
    formData.value = {
        id: undefined,
        number: '',
        typeId: undefined,
        buildingId: undefined,
        floor: undefined,
        accessType: [],
        deviceId: '',
        status: 4,
        externalSubStatus: 0,
        roomType: 1,
        subscribeNum:1
    }
    formRef.value?.resetFields()
}

// 密码新增
function handlePasswordAdd() {
  passwordDialog.value.passwordVisible = true;
}

// 获取密码列表
async function getPasswordList(roomId:any) {
  passwordLoading.value = true;
  try {
    console.log("roomId:" + roomId)
    queryParams.roomId = roomId;
    const passwordListData = await roomPasswordApi.getPasswordDatePage(queryParams)
    passwordList.value = passwordListData.list
    passwordTotal.value = passwordListData.total
  } finally {
    passwordLoading.value = false
  }
}

// 专属空间密码新增：弹框数据
const passwordDialog = ref({
  roomId: initParam.roomId,
  passwordVisible: false,
  dateTime: [],
  password: undefined,
  remark: undefined
})

function handlePasswordDelete(row) {
  useConfirm(t("common.delMessage"), async () => {
    await roomPasswordApi.deleteExclusivePassword(row.id);
    getPasswordList(initParam.roomId).finally(() => useMessage(t('common.delSuccess')));
  });
}
</script>
